1850E - Cardboard for Pictures - CodeForces Solution


binary search implementation math

Please click on ads to support us..

Python Code:

import math

def eq(a,b,c):
    x=b**2-(4*a*c)
    y=math.sqrt(x)
    ans=(-b+y)/(2*a)
    return ans

t=int(input())
for i in range(0,t):
    x=0
    y=0
    nn,kk=input().split()
    n=int(nn)
    k=int(kk)
    li=list(map(int,input().split(' ')))
    for j in li:
        x+=j
        y+=j**2
    a=4*n
    b=4*x
    c=y-int(k)
    ans=eq(a,b,c)
    an=int(ans)
    print(f"{an}\n")

C++ Code:

#include "bits/stdc++.h"
using namespace std;
 
#define ll long long
 
#define          all(v)              v.begin(), v.end()
#define         rall(v)              v.rbegin(),v.rend()
 
#define            pb                push_back
#define          sz(a)               (int)a.size()
 
#define int long long
 
void solve() {
    int n, c; cin >> n >> c;
    vector<int> a(n);
    for(int i = 0; i < n; ++i) cin >> a[i];
    int l = 1, r = 1e9;
    while(l <= r) {
        int mid = l + (r - l) / 2;
        int sumall = 0;
        for(int i = 0; i < n; ++i) {
            sumall += (a[i] + 2 * mid) * (a[i] + 2 * mid);
            if(sumall > c) break;
        }
        if(sumall == c) {
            cout << mid << "\n";
            return;
        }
        if(sumall > c) {
            r = mid - 1;
        } else {
            l = mid + 1;
        }
    }
}   
 
int32_t main() {
    ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int t = 1;
    cin >> t;
    while(t--) {
        solve();
    }
}


Comments

Submit
0 Comments
More Questions

Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game
Char Sum
Two Strings
Anagrams
Prime Number
Lexical Sorting Reloaded
1514A - Perfectly Imperfect Array
580A- Kefa and First Steps
1472B- Fair Division
996A - Hit the Lottery
MSNSADM1 Football
MATCHES Playing with Matches